package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1. 校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        int operation = dto.getOperation();
        if(operation!=0 && operation!=1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"操作方式错误");
        }
        //判断是否关注
        int loginUserId = user.getId();
        int authorUserId =dto.getAuthorApUserId();

        if(operation==0){
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorUserId));
            if(score!=null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"已关注 不可重复关注");
            }
            if(loginUserId==authorUserId){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"不能关注自己");
            }
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST+loginUserId,String.valueOf(authorUserId),System.currentTimeMillis());
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST+authorUserId,String.valueOf(loginUserId),System.currentTimeMillis());
        }else {
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+loginUserId,String.valueOf(authorUserId));
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST+authorUserId,String.valueOf(loginUserId));
        }

        return null;
    }
}
